package com.xuwang.service.impl;

import com.xuwang.Common.Constast;
import com.xuwang.Util.JWTutil;
import com.xuwang.Util.TableResult;
import com.xuwang.mapper.RestaurantMapper;
import com.xuwang.pojo.Comment;
import com.xuwang.pojo.Restaurant;
import com.xuwang.pojo.RestaurantFood;
import com.xuwang.pojo.User;
import com.xuwang.service.RestaurantService;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * (Restaurant)表服务实现类
 *
 * @author smallseven
 * @version 1.0
 * @since 2021-08-31 15:29:52
 */
@Service
public class RestaurantServiceImpl implements RestaurantService {
    @Resource
    private RestaurantMapper restaurantMapper;

    /**
     * 更加token查询用户等级根据等级来展示不同内容
     *
     * @param token
     * @return
     */
    @Override
    public TableResult<List> showIndex(String token) {
        //获取用户名
        String username = JWTutil.getUserName(token);

        //根据用户名获取用户等级和用户id
        User user = restaurantMapper.findIdentityByName(username);
        //获取用户等级
        int idEntity = user.getIdentity();
        //获取用户id
        int id = user.getId();
        List<Restaurant> restaurantList;
        //根据用户等级来显示不同内容
        if (idEntity == 0) {
            //查询该代表的相关id
            User userInfo = restaurantMapper.findRestaurantByUserId(id);
            //根据餐馆id查出餐馆信息
            //id集合
            List<Integer> ids = new ArrayList<>();
            List<Restaurant> restaurants = userInfo.getRestaurants();
            for (Restaurant restaurant : restaurants) {
                ids.add(restaurant.getId());
            }
            restaurantList = restaurantMapper.findRestaurantById(ids);
            //组装菜品id然后查找菜系
            for (Restaurant restaurant : restaurantList) {
                //获取到当前餐馆的所有食物
                List<RestaurantFood> restaurantFoods = restaurant.getRestaurantFoods();
                //当前所有餐馆的菜系id集合
                List<Integer> idList = new ArrayList<>();
                for (RestaurantFood restaurantFood : restaurantFoods) {
                    Integer id1 = restaurantFood.getId();
                    idList.add(id1);
                }
                //查找当前餐馆的菜系分类
                List<String> kindList = restaurantMapper.findAllFoodKind(idList);
                String kindStr = " ";
                for (String kindName : kindList) {
                    kindStr = kindName + " " + kindStr;
                }
                restaurant.setAllFoodKind(kindStr);
            }


        }
        //普通用户和政府人员看到的信息
        else {
            restaurantList = restaurantMapper.findAllRestaurant();
            //组装菜品id然后查找菜系
            for (Restaurant restaurant : restaurantList) {
                List<Integer> idList = new ArrayList<>();
                List<RestaurantFood> restaurantFoods = restaurant.getRestaurantFoods();
                for (RestaurantFood restaurantFood : restaurantFoods) {
                    Integer id1 = restaurantFood.getId();
                    idList.add(id1);
                }
                //查找当前餐馆的菜系分类
                List<String> kindList = restaurantMapper.findAllFoodKind(idList);
                String kindStr = " ";
                for (String kindName : kindList) {
                    kindStr = kindName + " " + kindStr;
                }
                restaurant.setAllFoodKind(kindStr);
            }
        }
        TableResult<List> result = new TableResult<>(200, "查询成功", 1, restaurantList);
        return result;
    }

    /**
     * 展示所有菜品信息
     *
     * @return
     */
    @Override
    public TableResult<List> showFood() {
        TableResult<List> result;
        List<RestaurantFood> restaurantFoodList;
        restaurantFoodList = restaurantMapper.findAllFood();
        for (RestaurantFood restaurantFood : restaurantFoodList) {
            //查询评论次数
            int count = restaurantMapper.findCountOfComment(restaurantFood.getId());
            restaurantFood.setCommentCount(count);
            //查询该菜的评论总分
            Double score = restaurantMapper.findAvgOfComment(restaurantFood.getId());
            restaurantFood.setAvgSocre(score);
        }
        result = new TableResult<>(200, "获取食品信息成功", restaurantFoodList.size(), restaurantFoodList);
        return result;
    }

    /**
     * 冒泡排序根据评价平均分来降序排序
     *
     * @return
     */
    @Override
    public TableResult<List> showRank() {
        TableResult<List> result = showFood();
        List<RestaurantFood> data = result.getData();
        for (int i = 0; i < data.size() - 1; i++) {
            for (int j = 0; j < data.size() - i - 1; j++) {
                //交换对象
                if (data.get(j).getAvgSocre() < data.get(j + 1).getAvgSocre()) {
                    //临时对象
                    RestaurantFood restaurantFood = new RestaurantFood();
                    restaurantFood = data.get(j);
                    data.set(j, data.get(j + 1));
                    data.set(j + 1, restaurantFood);
                }
            }
        }
        TableResult<List> res = new TableResult<>(200, "获取食品排行信息成功", data.size(), data);
        return res;
    }

    /**
     * 增加新菜品
     * @param restaurantFood
     * @param username
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public TableResult<String> insertFood(RestaurantFood restaurantFood, String username) {
        TableResult<String> res ;
        //根据用户名获取用户等级和用户id
        User user = restaurantMapper.findIdentityByName(username);
        //获取用户id
        int id = user.getId();
        //查询菜品的菜系
        int kindId = restaurantMapper.findFoodKindByName(restaurantFood.getFoodKind());
        restaurantFood.setFoodKindId(kindId);
        //根据用户查询餐馆id
       int restaurantId= restaurantMapper.findRestaurantIdByUserId(id);
        int isSuccess = restaurantMapper.insertFood(restaurantFood, restaurantId);
        //插入菜品成功之后
        if (isSuccess == 1) {
            //向食品评论中添加初始评论
            Comment comment = new Comment();
            Timestamp date = new Timestamp(System.currentTimeMillis());
            comment.setCommentContent("新菜上线");
            comment.setScore(3.0);
            comment.setCommentEnvironment(3.0);
            comment.setCommentServe(3.0);
            comment.setCommentTaste(3.0);
            comment.setUserId(0);
            comment.setObjId(restaurantFood.getId());
            comment.setTime(date);
           int flag= restaurantMapper.insertComment(comment);
        }
        res=new TableResult<>(200,"添加成功",1,"");
        return res;
    }

    /**
     * 展示个人信息
     * @param token
     * @return
     */
    @Override
    public TableResult<List> showMyInfo(String token) {
        //获取用户名
        String username = JWTutil.getUserName(token);
        //根据用户名获取用户等级和用户id
        User user = restaurantMapper.findIdentityByName(username);
        //获取用户等级
        int idEntity = user.getIdentity();
        //获取用户id
        int id = user.getId();
        List<User> resuUserList=restaurantMapper.showMyInfo(id);
        TableResult<List> res = new TableResult<>(200,"查询用户评论成功",1,resuUserList);
        return res;
    }

    /**
     * 展示单独的菜品信息：所在餐馆,菜名，总排行，总评分平均值和各个评论内容
     * @param id
     * @return
     */
    @Override
    public TableResult<RestaurantFood> showOneFood(Integer id) {
        //获取总排行
        int rank = 1;
        TableResult<List> result = showRank();
        List<RestaurantFood> data = result.getData();
        for(int i=0;i<data.size()-1; i++){
            if (id.equals(data.get(i).getId())){
                rank=i+1;
                break;
            }
        }
        RestaurantFood restaurantFood= restaurantMapper.showOneFood(id);
        //将排行封装进去
        restaurantFood.setRank(rank);
        //获取菜品的历史评论
        List<Comment> commentList=restaurantMapper.findCommentOfFood(id);
        restaurantFood.setComment(commentList);
        return new TableResult<>(200,"获取该菜品信息成功",1,restaurantFood);
    }

    /**
     * 新增用户对菜品的评论
     * @param  comment
     * @param  username
     * @return
     */
    @Override
    public TableResult<String> insertComment(Comment comment,String username) {
       TableResult<String> tableResult ;
        //根据用户名获取用户等级和用户id
        User user = restaurantMapper.findIdentityByName(username);
        //获取用户id
        int id = user.getId();
        comment.setUserId(id);
        //设置评论总分
        Double sumScore=(comment.getCommentServe()+comment.getCommentEnvironment()+comment.getCommentTaste())/3;
        //保留两位小数
        sumScore=  (double) Math.round(sumScore * 100) / 100;
        comment.setScore(sumScore);
        //设置当前时间
        Timestamp time=new Timestamp(System.currentTimeMillis());
        comment.setTime(time);
        int isSuccess =restaurantMapper.insertComment(comment);
        if (isSuccess ==1) {
            tableResult=new TableResult(200, Constast.INSERT_COMPLETE,1,null);
        }else {
            tableResult=new TableResult(500, Constast.INSERT_ERROR,1,"");
        }
        return tableResult;
    }

    /**
     * 修改菜品图片信息
     * @param id
     * @param src
     * @return
     */
    @Override
    public TableResult<String> uploadFoodInfo(Integer id,String src) {
        TableResult<String> tableResult ;
       int isSuccess= restaurantMapper.uploadFoodInfo(id,src);
       if (isSuccess == 1) {
           tableResult=new TableResult(200,"修改菜品信息成功",1,"");
       }
        else {
           tableResult=new TableResult(500,"修改菜品信息失败",0,"");
        }
        return tableResult;
    }

    @Override
    public TableResult<String> uploadFoodOtherInfo(RestaurantFood restaurantFood) {
        TableResult<String> tableResult ;
        int isSuccess= restaurantMapper.uploadFoodOtherInfo(restaurantFood);
        if (isSuccess == 1) {
            tableResult=new TableResult(200,"修改菜品基础信息成功",1,"");
        }
        else {
            tableResult=new TableResult(500,"修改菜品基础信息失败",0,"");
        }
        return tableResult;

    }

    /**
     * 修改餐馆图片信息
     * @param id
     * @param src
     * @return
     */
    @Override
    public TableResult<String> uploadRestaurantImgInfo(Integer id, String src) {
        TableResult<String> tableResult ;
        int isSuccess= restaurantMapper.uploadRestaurantInfo(id,src);
        if (isSuccess == 1) {
            tableResult=new TableResult(200,"修改餐馆信息成功",1,"");
        }
        else {
            tableResult=new TableResult(500,"修改餐馆信息失败",0,"");
        }
        return tableResult;
    }

    /**
     * 修改餐馆基础信息
     * @param restaurant
     * @return
     */
    @Override
    public TableResult<String> uploadRestaurantOtherInfo(Restaurant restaurant) {
        TableResult<String> tableResult ;
        int isSuccess= restaurantMapper.uploadRestaurantOtherInfo(restaurant);
        if (isSuccess == 1) {
            tableResult=new TableResult(200,"修改菜品基础信息成功",1,"");
        }
        else {
            tableResult=new TableResult(500,"修改菜品基础信息失败",0,"");
        }
        return tableResult;

    }
}
